<?php

namespace My\Controller;

use Utuo\BackgroundController;

class SiteController extends BackgroundController {
	protected function _initialize() {
		$this->setControllerTitle("微官网");
		$this->setActionTitle(array(
				'index' => '网站设置',
				'wechat' => '微信回复设置',
				'url' => '网站地址' 
		));
		
		$this->setActionNav('index,wechat,url');
	}
	
	// 网站设置
	public function indexAction() {
		$m = M("Site");
		if (!$m->where("id=%d", $this->aid)->count()) {
			false === $m->add(array(
					'id' => $this->aid,
					'cid' => $this->aid,
					'name' => $this->aname 
			)) and $this->ajaxSuccess("基本信息插入失败");
		}
		
		$site = $m->find($this->aid);
		$modelId = M("Model")->where("tag='Site'")->getField("id");
		$themeLists = M()->table("(select this0.* from ( 
								  select * 
								  from __THEME__ this0 
								  where (this0.partner in ( SELECT partner FROM __CUSTOMER__ where id = {$this->aid} ) or this0.partner = 0) and this0.model_id=$modelId
								) this0
								where this0.customer in(0, {$this->aid})) this1")->getField("this1.id, this1.name");
		$site["themesOptions"] = $this->getOption($themeLists, $site['theme'], "==请选择主题==");
		$this->assign("site", $site);
		$this->display();
	}
	
	// 微信回复设置
	public function wechatAction() {
		$wechat_rule = '__site_rule__';
		$d = D('WechatReply');
		$reply = $d->getReply($this->aid, $wechat_rule);
		if (!$reply) {
			$url = uu($this->aid, 'Home', 'Site', 'index', "sid={$this->aid}", true);
			$id = $d->setKeywordReply($this->aid, $wechat_rule, '微官网', '微官网', '点击进入【微官网】', '', $url);
			$id && $reply = $d->find($id);
		}
		$reply['keyword'] = trim($reply['keyword'], ' ,');
		$this->assign('reply', $reply);
		$this->display();
	}
	
	// 提交微信回复
	public function wechatPostAction() {
		$d = D('WechatReply');
		if ($d->create()) {
			$d->keyword = $d->parseKeyword($d->keyword);
			if ($d->save()) {
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError();
	}
	
	// 首页地址
	public function urlAction() {
		$site['url'] = uu($this->aid, 'Home', 'Site', 'index', "sid={$this->aid}", true);
		$this->assign('site', $site);
		$this->display();
	}
	
	// 提交设置
	public function indexPostAction() {
		$d = D("Site");
		if ($d->create()) {
			$d->id = $this->aid;
			$d->cid = $this->aid;
			if (false !== $d->save()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError($d->getError());
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
}